<?php

namespace App\Http\Controllers;

use App\Comment;
use App\Formitem;
use App\FY\FeiyuApi;
use App\Keep;
use App\Likes;
use App\Live;
use App\LiveUser;
use App\Message;
use App\Form;
use App\Notice;
use App\ShopCat;
use App\ShopCode;
use App\ShopCoupon;
use App\ShopGoods;
use App\Shopmeta;
use App\ShopOrder;
use App\ShopUser;
use App\SMS\SendFormSMS;
use App\SMS\SendTemplateSMS;
use App\SMS\SendShopSMS;
use App\TagGroup;
use App\Post;
use App\Postmeta;
use App\Tag;
use App\User;
use App\Usermeta;
use App\WxPay\JsApi_pub;
use App\WxPay\Notify_pub;
use App\WxPay\UnifiedOrder_pub;
use App\Xcx\WXBizDataCrypt;
use Symfony\Component\HttpFoundation\Request;
use QrCode;

// add log lib
use Illuminate\Support\Facades\Log;

class XcxApi extends Controller{
    private function SessionKey(){
        $chaRid = strtoupper(md5(uniqid(mt_rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = substr($chaRid, 0, 8).$hyphen
            .substr($chaRid, 8, 4).$hyphen
            .substr($chaRid,12, 4).$hyphen
            .substr($chaRid,16, 4).$hyphen
            .substr($chaRid,20,12);
        return $uuid;
    }
    private function createQR($user_id){
        $key = $this->SessionKey();
        $meta = Usermeta::where("user_id",$user_id)->where("key","QRCode")->first();
        if(!$meta){
            $meta = new Usermeta();
        }
        $meta->user_id = $user_id;
        $meta->key = 'QRCode';
        $meta->value = $key;
        if($meta->save()){
            QrCode::format('png')->size(300)->generate($key,public_path('upload/user/'.$user_id.'.png'));
            $meta = Usermeta::where("user_id",$user_id)->where("key","QR")->first();
            if(!$meta){
                $meta = new Usermeta();
            }
            $meta->user_id = $user_id;
            $meta->key = 'QR';
            $meta->value = asset('upload/user/'.$user_id.'.png');
            return $meta->save();
        }
        return 0;

    }
    private function RandomString()
    {
        $characters = '0123456789';
        $rand = '';
        for ($i = 0; $i < 6; $i++) {
            $rand = $rand.$characters[rand(0, 9)];
        }
        return $rand;
    }
    private function TimeStatus($now,$id){
        $start = Postmeta::where("post_id",$id)->where("key","activeTime")->first();
        $status = 0;
        if($start){
            if(strtotime($start->value)>$now){
                $status = 1;
            }else{
                $end = Postmeta::where("post_id",$id)->where("key","endTime")->first();
                if($end){
                    if(strtotime($end->value)>$now) {
                        $status = 2;
                    }
                }
            }
        }
        return $status;
    }
    public function WxLogin(Request $request){
        $data = $request->input();
        $code = $data['code'];
        if($code==='skXcx'){
            $appID = 'wxfca50078ea0ff5c1';
            #$appSecret = 'abbf5d3bc574fc27fe7802b6abfa1d0a';
            $appSecret = '2b9ea75c582a6b7b6be2a40aefea1327';
            $js_code = $data['js_code'];
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appID.'&secret='.$appSecret.'&js_code='.$js_code.'&grant_type=authorization_code';
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            $json = curl_exec($ch);
            curl_close($ch);
            $json = json_decode($json);
            $session = '';
            $session_time = '';
            $user_id = 0;
            $user_level = 0;
            $QR = '';
	    // debug log
	    Log::debug('wechat auth response ==>' . json_encode($json));
            
	    if ( !isset($json->errcode) ){
                $session_key = $json->session_key;
                $User = User::where("openid",$json->openid)->first();
	        // debug log
		#Log::debug('user model select ==>' . json_encode($User));

                $session = $this->SessionKey();
                $session_time = time()+604800;

                if($User) {
                    $user_id = $User->id;
                    $user_level = $User->level;
                    $User->session = $session;
                    $User->session_time = $session_time;
                    $meta = Usermeta::where("user_id",$user_id)->where("key","QR")->first();
                    if(!$meta) {
                        $QR = $this->createQR($user_id);
                    } else {
                        $QR = $meta->value;
                    }
                    if(!$User->update(['session' => $session, 'session_time' => $session_time])) {
                        return '{"user_id":0,"user_level":0,"session":"","session_time":""}';
                    }
                } else {
                    $encryptedData = $data['encryptedData'];
                    $encryptedData = preg_replace('/\%2B/','+',$encryptedData);
                    $iv = $data['iv'];
                    if($iv&&$encryptedData){
                        $pc = new WXBizDataCrypt($appID, $session_key);
                        $errCode = $pc->decryptData($encryptedData, $iv, $data );
                        if(!$errCode){
                            $json = json_decode($data);
                            $open_id = $json->openId;
                            $User = User::where("openid",$open_id)->first();
                            if(!$User){
                                $randStr = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
                                $rand = substr($randStr,0,6);

                                $User = new User();
                                $User->name = preg_replace_callback('/./u',function (array $match) {return strlen($match[0]) >= 4 ? '' : $match[0];},$json->nickName);
                                $User->password = bcrypt($rand);
                                $User->company = "";
                                $User->content = "";
                                $User->openid = $open_id;
                                $User->session = $session;
                                $User->session_time = $session_time;
                                if($User->save()){
                                    $avatar = $json->avatarUrl;
                                    $UserMeta =  new Usermeta();
                                    $UserMeta->user_id = $User->id;
                                    $UserMeta->key = 'avatar';
                                    $UserMeta->value = $avatar;
                                    $UserMeta->save();
                                    $user_id = $User->id;
                                    $QR = $this->createQR($user_id);
                                }else{
                                    return '{"user_id":0,"user_level":0,"session":"","session_time":""}';
                                }
                            }
                        }
                    }
                }
            }
            return '{"user_id":'.$user_id.',"user_level":'.$user_level.',"session":"'.$session.'","session_time":"'.$session_time.'","QR":"'.$QR.'"}';
        }
        return '{"user_id":0,"user_level":0,"session":"","session_time":""}';
    }
    public function GetSession(Request $request){
        $data = $request->input();
        $code = $data['code'];
        if($code==='sessionXcx'){
            $session = $data['session'];
            $User = User::where("session",$session)->first();
            $session_time = time();
            $user_id = 0;
            $user_level = 0;
            $session = '';
            if($User&&$session_time>$User->session_time){
                $user_id = $User->id;
                $user_level = $User->level;
                $session_time += 604800;
                $session = $this->SessionKey();
                if(!$User->save()){
                    return '{"user_id":0,"user_level":0,"session":"","session_time":""}';
                }
            }
            return '{"user_id":'.$user_id.',"user_level":'.$user_level.',"session":"'.$session.'","session_time":"'.$session_time.'"}';
        }
        return '{"user_id":0,"user_level":0,"session":"","session_time":""}';
    }
    public function verifySession(Request $request){
        $data = $request->input();
        $code = $data['code'];
        if($code==='sessionXcx'){
            $session = $data['session'];
            $User = User::where("session",$session)->first();
            if($User){
                return $User->level;
            }
        }
        return "no";
    }
    public function GetView(Request $request){
        $data = $request->input();
        $id = $data['id'];
        $view = Post::find($id);
        if(isset($data['con'])&&$data['con']){
            $_r = $view->content;
        }else{
        $view->content = preg_replace('/&nbsp;/', ' ', $view->content);
        $_arr = preg_split('/(<img.*?>)/i', $view->content, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
        $_r = array();
        foreach($_arr as $_txt) {
            if(substr($_txt, 0, 4) == '<img') {
                $_matchs = array();
                preg_match('/<img.*?src="(.*?)"/i', $_txt, $_matchs);
                $_txt = $_matchs[1];
                $_r[]= array('type'=>'img', 'data'=>$_txt);
            }else {
                $_r[]= array('type'=>'txt', 'data'=>$_txt);
            }
        }
        }
        $comment = Comment::where('post_id',$id)->where('parent',0)->orderBy('id', 'desc')->get();
        $comment_id = array();
        $author = array();
        $avatar = array();
        $content = array();
        $time = array();
        $count = array();
        if($comment){
            foreach ($comment as $c){
                array_push($comment_id,$c->id);
                array_push($author,$c->name);
                array_push($content,$c->content);
                array_push($time,$c->created_at->format('Y-m-d'));
                array_push($count,Comment::where("parent",$c->id)->count());
                $a = Usermeta::where("user_id",$c->user_id)->where("key","avatar")->first();
                array_push($avatar,$a->value);
            }
        }
        $comments = array('id'=>$comment_id,'author'=>$author,'avatar'=>$avatar,'content'=>$content,'time'=>$time,'count'=>$count);
        $con= array('title'=>$view->title,'time'=>$view->created_at->format('Y-m-d'),'author'=>$view->author,'video'=>'','content'=> $_r,'cover'=> $view->cover);
        $keepCount = Keep::where('post_id',$id)->where('status',1)->count();
        $keepStatus = 0;
        if($keepCount){
            $keepStatus = Keep::where('post_id',$id)->where('user_id',$data['uid'])->where('status',1)->first();
        }
        $Keep = array('count'=>$keepCount,'status'=>($keepStatus?1:0));
        $meta = Array();
        $Postmeta = Postmeta::where("post_id",$id)->get();
        foreach ($Postmeta as $m){
            $meta["$m->key"]= $m->value;
        }
        if($data['type']=='service'){
            if(isset($meta['startService'])&&isset($meta['endService'])){
                $now_time  = date('H:i');
                $meta['callStatus']= $now_time>$meta['startService']&&$now_time<$meta['endService']?1:0;
            }else{
                $meta['callStatus']= 0;
            }
            $_Tag = Tag::find($view->tag);
            $meta['TagName']= $_Tag->name;
        }
        $_data= array('content'=>$con,'comment'=>$comments,'keep'=>$Keep,'meta'=>$meta);
        $view->view++;
        $view->save();
        return json_encode($_data, JSON_UNESCAPED_UNICODE);
    }
    public function PostComment(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $Comment = new Comment();
            $Comment->post_id = $data["id"];
            $Comment->user_id = $User->id;
            $Comment->name = $User->name;
            $Comment->content = $data["comment"];
            if($request->has('parent')){
                $Comment->parent = $data["parent"];
            }
            if($Comment->save()){
                return $Comment->id;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }
    public function ChangeWiget(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            if($data["type"]=="keep"){
                $Wiget = Keep::where("user_id",$data["uid"])->where("post_id",$data["id"])->first();
                if(!$Wiget){
                    $Wiget = New Keep();
                    $Wiget->user_id = $data["uid"];
                    $Wiget->post_id = $data["id"];
                }
                $Wiget->status = $data["status"];
            }else{
                $Wiget = Likes::where("user_id",$data["uid"])->where("post_id",$data["id"])->first();
                if(!$Wiget){
                    $Wiget = New Likes();
                    $Wiget->user_id = $data["uid"];
                    $Wiget->post_id = $data["id"];
                }
                $Wiget->status = $data["status"];
            }
            if($Wiget->save()){
                return $Wiget->id;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }
    public function GetComment(Request $request){
        $data = $request->input();
        $id = $data['id'];
        $com = Comment::find($id);

        if($com){
            $a = Usermeta::where("user_id",$com->user_id)->where("key","avatar")->first();
            $comArr = Array('id'=>$id,'author'=>$com->name,'avatar'=>$a->value,'content'=>$com->content,'time'=>$com->created_at->format('Y-m-d H:i'));

            $comments = Comment::where('parent',$id)->get();
            $comment_id = array();
            $author = array();
            $avatar = array();
            $content = array();
            $time = array();
            if($comments){
                foreach ($comments as $c){
                    array_push($comment_id,$c->id);
                    array_push($author,$c->name);
                    array_push($content,$c->content);
                    array_push($time,$c->created_at->format('Y-m-d H:i'));
                    $a = Usermeta::where("user_id",$c->user_id)->where("key","avatar")->first();
                    array_push($avatar,$a->value);
                }
            }
            $comments = array('id'=>$comment_id,'author'=>$author,'avatar'=>$avatar,'content'=>$content,'time'=>$time);
            $_data= array('content'=>$comArr,'comment'=>$comments);
            return json_encode($_data, JSON_UNESCAPED_UNICODE);
        }else{
            return 0;
        }
    }
    public function HomePage(Request $request){
        $data = $request->input();
        $type = $data["type"];
        $SwipeLength = $request->has('swipe')?$data["swipe"]:0;
        $ConId = $request->has('conId')?$data["conId"]:0;
        $TopLength= $request->has('top')?$data["top"]:0;

        $Swipe_id = Array();
        $Swipe_cover = Array();
        $Swipe_title = Array();
        $Swipe_status = Array();

        $content_id = Array();
        $content_cover = Array();
        $content_title = Array();
        $content_time = Array();
        $content_status = Array();
        $content_tag = Array();
        $content_video = Array();
        $now = time();
        if($SwipeLength == 0){
            $Swipe = Post::where("xcx",$type)->where("level",2)->where("status",1)->orderBy('id', 'desc')->get();
            if($Swipe){
                foreach ($Swipe as $s){
                    array_push($Swipe_id,$s->id);
                    array_push($Swipe_cover,$s->cover);
                    array_push($Swipe_title,$s->title);
                    array_push($Swipe_status,$this->TimeStatus($now,$s->id));
                }
            }
        }
        if($TopLength == 0){
            $TopNew = Post::where("xcx",$type)->where("level",1)->where("status",1)->orderBy('id', 'desc')->get();
            if($TopNew){
                foreach ($TopNew as $t){
                    array_push($content_id,$t->id);
                    array_push($content_cover,$t->cover);
                    array_push($content_title,$t->title);
                    array_push($content_time,$t->created_at->format('Y-m-d H:i'));
                    array_push($content_status,$this->TimeStatus($now,$t->id));
                    $Tag = Tag::find($t->tag);
                    $name = $Tag?$Tag->name:'活动路演';
                    array_push($content_tag,$name);
                    $video = Postmeta::where("post_id",$t->id)->where("key","video")->first();
                    $v = $video?1:0;
                    array_push($content_video,$v);
                }
            }
        }
        $SwipeArr = array('id'=>$Swipe_id,'pic'=>$Swipe_cover,'title'=>$Swipe_title,'status'=>$Swipe_status);

        if($ConId == 0){
            $content = Post::where("xcx",$type)->where("level",0)->where("status",1)->orderBy('id', 'desc')->simplePaginate(20);
        }else{
            $content = Post::where("xcx",$type)->where("id","<",$ConId)->where("level",0)->where("status",1)->orderBy('id', 'desc')->simplePaginate(20);
        }
        if($content){
            foreach ($content as $c){
                array_push($content_id,$c->id);
                array_push($content_cover,$c->cover);
                array_push($content_title,$c->title);
                array_push($content_time,$c->created_at->format('Y-m-d H:i'));
                array_push($content_status,$this->TimeStatus($now,$c->id));
                $Tag = Tag::find($c->tag);
                $name = $Tag?$Tag->name:'活动路演';
                array_push($content_tag,$name);
                $video = Postmeta::where("post_id",$c->id)->where("key","video")->first();
                $v = $video?1:0;
                array_push($content_video,$v);
            }
        }
        $conArr = array('id'=>$content_id,'pic'=>$content_cover,'title'=>$content_title,'time'=>$content_time,'status'=>$content_status,'tag'=>$content_tag,'video'=>$content_video);
        $_data= array('swipe'=>$SwipeArr,'content'=>$conArr);
        return json_encode($_data, JSON_UNESCAPED_UNICODE);
    }
    public function getService(Request $request){
        $data = $request->input();
        $id = $data["id"];
        $name = Array();
        $arrId = Array();
        $cover = Array();
        $group = Array();
        if($id!=0){
            $_cat = isset($data["cat"])?$data["cat"]:"";
            if($_cat=='shop'){
                $List = ShopUser::where("status",1)->orderBy('created_at', 'asc')->get();
                foreach ($List as $l){
                    array_push($arrId,$l->id);
                    array_push($name,$l->name);
                    array_push($cover,$l->cover);
                }
                $_data = Array("id"=>$arrId,"name"=>$name,"cover"=>$cover,"group"=>$group,"meta"=>[],"menu"=>Array("filter"=>[],"id"=>[],"name"=>[]));
            }elseif($_cat=='coupon'){
                $tagId = Tag::where("type","couponCat")->get();
                $tagIdArr = [];
                $n = Array();
                $Id = Array();
                $f_name= Array();
                foreach ($tagId as $_t) {
                    $Filter = Tag::where('parent_id',$_t->id)->get();
                    array_push($tagIdArr,$_t->id);
                    $_Id = Array();
                    $_n = Array();
                    foreach ($Filter as $f){
                        array_push($_Id,$f->id);
                        array_push($_n,$f->name);
                    }
                    array_push($Id,$_Id);
                    array_push($n,$_n);
                    array_push($f_name,$_t->name);
                }
                $List = Post::whereIn("tag",$tagIdArr)->where("status",1)->orderBy('created_at', 'asc')->get();
                $metaArr = Array();
                $now = date('Y-m-d');
                $limit = '';
                if(isset($data["shop"])&&$data["shop"]!=0){
                    $limit = Shopmeta::where("shop_id",$data["shop"])->where("key","coupon_use_limit")->first();
                }
                foreach ($List as $l){
                    $meta = Array();
                    $endTime = Postmeta::where("post_id",$l->id)->where("key","endCoupon")->first();
                    if($endTime&&$endTime->value<$now){
                        continue;
                    }
                    if(isset($data["shop"])&&$data["shop"]!=0){
                        $coupon_id = Postmeta::where("post_id",$l->id)->where("key","coupon_id")->first();
                        if($coupon_id&&$coupon_id->value!=$data["shop"]){
                            if($limit){
                                continue;
                            }elseif($coupon_id->value!=0){
                                continue;
                            }
                        }
                    }
                    array_push($arrId,$l->id);
                    array_push($name,$l->title);
                    $Postmeta = Postmeta::where("post_id",$l->id)->whereIn("key",["coupon_discount","coupon_cash","startCoupon","endCoupon","coupon_num","coupon_full","coupon_cut"])->get();
                    foreach ($Postmeta as $m){
                        $meta["$m->key"]= $m->value;
                    }
                    $meta["tag"]=$l->tag;
                    array_push($metaArr,$meta);
                    $TagGroup = TagGroup::where("post_id",$l->id)->get();
                    $TagArr = [];
                    foreach ($TagGroup as $g){
                        array_push($TagArr,$g->tag);
                    }
                    array_push($group,$TagArr);
                }
                $_data = Array("id"=>$arrId,"name"=>$name,"cover"=>$cover,"group"=>$group,"meta"=>$metaArr,"menu"=>Array("filter"=>$f_name,"id"=>$Id,"name"=>$n));
            }else{
            $List = Post::where("tag",$id)->where("status",1)->where("level",1)->orderBy('created_at', 'asc')->get();
            $metaArr = Array();
            foreach ($List as $l){
                $meta = Array();
                array_push($arrId,$l->id);
                array_push($name,$l->title);
                array_push($cover,$l->cover);
                $Postmeta = Postmeta::where("post_id",$l->id)->get();
                foreach ($Postmeta as $m){
                    $meta["$m->key"]= $m->value;
                }
                array_push($metaArr,$meta);
                $TagGroup = TagGroup::where("post_id",$l->id)->get();
                $TagArr = [];
                foreach ($TagGroup as $g){
                    array_push($TagArr,$g->tag);
                }
                array_push($group,$TagArr);
            }
            $List = Post::where("tag",$id)->where("status",1)->where("level",0)->orderBy('created_at', 'asc')->get();
            foreach ($List as $l){
                $meta = Array();
                array_push($arrId,$l->id);
                array_push($name,$l->title);
                array_push($cover,$l->cover);
                $Postmeta = Postmeta::where("post_id",$l->id)->get();
                foreach ($Postmeta as $m){
                    $meta["$m->key"]= $m->value;
                }
                array_push($metaArr,$meta);
                $TagGroup = TagGroup::where("post_id",$l->id)->get();
                $TagArr = [];
                foreach ($TagGroup as $g){
                    array_push($TagArr,$g->tag);
                }
                array_push($group,$TagArr);
            }
            $Filter = Tag::where('parent_id',$id)->get();
            $tag = Tag::find($id);
            $n = Array();
            $Id = Array();
            foreach ($Filter as $f){
                array_push($Id,$f->id);
                array_push($n,$f->name);
            }
            $_data = Array("id"=>$arrId,"name"=>$name,"cover"=>$cover,"group"=>$group,"meta"=>$metaArr,"menu"=>Array("filter"=>$tag->filter,"id"=>$Id,"name"=>$n));
            }
        }else{
            $Service = Tag::whereIn('type',['service','shop','coupon'])->orderBy('order_id', 'asc')->get();
            $count = Array();
            $type= Array();
            foreach ($Service as $s){
                array_push($arrId,$s->id);
                array_push($name,$s->name);
                array_push($cover,$s->more);
                array_push($type,$s->type);
                array_push($count,$s->type=='service'?Post::where("tag",$s->id)->where("status",1)->count():($s->type=='shop'?ShopUser::where("status",1)->count():Post::where("xcx",127)->where("status",1)->count()));
            }
            $_data = Array("id"=>$arrId,"name"=>$name,"cover"=>$cover,"count"=>$count,"type"=>$type);
        }
        return json_encode($_data, JSON_UNESCAPED_UNICODE);
    }
    public function GetKeep(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        $id_a = Array();
        $pic_a = Array();
        $title_a = Array();
        $time_a = Array();
        $author_a = Array();
        $cat_a = Array();
        $id_b = Array();
        $pic_b = Array();
        $title_b = Array();
        $time_b = Array();
        $author_b = Array();
        $cat_b = Array();
        $id_c = Array();
        $pic_c = Array();
        $title_c = Array();
        $time_c = Array();
        $author_c = Array();
        $cat_c = Array();
        if($User&&$User->id==$data["uid"]){
            $Tag = Tag::where("type","xcx")->get();
            $HomeNum = Array();
            $ServiceNum = Array();
            $ActiveNum = Array();
            $showCat = 0;
            foreach ($Tag as $t){
                if($t->name == '主页'){
                    array_push($HomeNum,$t->id);
                }elseif ($t->name == '路演'||$t->name == '活动'||$t->name == '回顾'){
                    array_push($ActiveNum,$t->id);
                    if($t->name == '活动'){$showCat = $t->id;}
                }elseif ($t->name == '服务'){
                    array_push($ServiceNum,$t->id);
                }
            }
            $keep = Keep::where("status",1)->where("user_id",$User->id)->orderBy('id', 'desc')->get();
            foreach ($keep as $k){
                $Post = Post::find($k->post_id);
                if($Post){
                    if(in_array($Post->xcx,$HomeNum)){
                        array_push($id_a,$Post->id);
                        array_push($pic_a,$Post->cover);
                        array_push($title_a,$Post->title);
                        array_push($time_a,$Post->created_at->format('Y-m-d H:i'));
                        array_push($author_a,$Post->author);
                        array_push($cat_a,0);
                    }elseif (in_array($Post->xcx,$ActiveNum)){
                        array_push($id_b,$Post->id);
                        array_push($pic_b,$Post->cover);
                        array_push($title_b,$Post->title);
                        array_push($time_b,$Post->created_at->format('Y-m-d H:i'));
                        array_push($author_b,$Post->author);
                        array_push($cat_b,($Post->xcx==$showCat?2:1));
                    }elseif (in_array($Post->xcx,$ServiceNum)){
                        array_push($id_c,$Post->id);
                        array_push($pic_c,$Post->cover);
                        array_push($title_c,$Post->title);
                        array_push($time_c,$Post->created_at->format('Y-m-d H:i'));
                        array_push($author_c,$Post->author);
                        array_push($cat_c,3);
                    }
                }
            }
        }
        $arr_a = Array("id"=>$id_a,"pic"=>$pic_a,"title"=>$title_a,"time"=>$time_a,"author"=>$author_a,"cat"=>$cat_a,);
        $arr_b = Array("id"=>$id_b,"pic"=>$pic_b,"title"=>$title_b,"time"=>$time_b,"author"=>$author_b,"cat"=>$cat_b,);
        $arr_c = Array("id"=>$id_c,"pic"=>$pic_c,"title"=>$title_c,"time"=>$time_c,"author"=>$author_c,"cat"=>$cat_c,);
        $_data = Array($arr_a,$arr_b,$arr_c);
        return json_encode($_data, JSON_UNESCAPED_UNICODE);
    }
    public function GetActive(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        $id_a = Array();
        $pic_a = Array();
        $title_a = Array();
        $time_a = Array();
        $author_a = Array();
        $cat_a = Array();
        $id_b = Array();
        $pic_b = Array();
        $title_b = Array();
        $time_b = Array();
        $author_b = Array();
        $cat_b = Array();
        if($User&&$User->id==$data["uid"]){
//        if(1){
            $Tag = Tag::where("type","xcx")->get();
            $TagNum = Array();
            $TagArr = Array();
            $showCat = 0;
            $serviceCat = 0;
            foreach ($Tag as $t){
                if ($t->name == '路演'||$t->name == '活动'||$t->name == '服务'){
                    $TagArr["$t->id"] = $t->name;
                    array_push($TagNum,$t->id);
                    if($t->name == '活动'){$showCat = $t->id;}elseif($t->name == '服务'){$serviceCat = $t->id;}
                }
            }
            $Post = Post::where("user_id",$User->id)->where(function($query) use ($TagNum){
                $query->where('xcx',$TagNum[0])
                    ->orWhere(function($query) use ($TagNum){
                        $query->where('xcx', $TagNum[1])
                            ->orWhere(function($query) use ($TagNum){
                            $query->where('xcx',$TagNum[2]);
                            });
                    });
            })->orderBy('id', 'desc')->get();
            foreach ($Post as $p){
                $now = time();
                $meta = Postmeta::where("post_id",$p->id)->where("key","activeTime")->first();
                if($meta){
                    if($p->status==1&&strtotime($meta->value)<$now){
                    array_push($id_a,$p->id);
                    array_push($pic_a,$p->cover);
                    array_push($title_a,$p->title);
                    array_push($time_a,$p->created_at->format('Y-m-d H:i'));
                    array_push($author_a,$p->author);
                    array_push($cat_a,($p->xcx==$serviceCat?3:($p->xcx==$showCat?2:1)));
                    }else{
                    array_push($id_b,$p->id);
                    array_push($pic_b,$p->cover);
                    array_push($title_b,$p->title);
                    array_push($time_b,$p->created_at->format('Y-m-d H:i'));
                    array_push($author_b,$p->author);
                    array_push($cat_a,($p->xcx==$serviceCat?3:($p->xcx==$showCat?2:1)));
                    }
                }
            }
        }
        $arr_a = Array("id"=>$id_a,"pic"=>$pic_a,"title"=>$title_a,"time"=>$time_a,"author"=>$author_a,"cat"=>$cat_a);
        $arr_b = Array("id"=>$id_b,"pic"=>$pic_b,"title"=>$title_b,"time"=>$time_b,"author"=>$author_b,"cat"=>$cat_b);
        $arr_c = Form::where("user_id",$data["uid"])->whereNotIn("type",["active","user"])->select('id','created_at')->orderBy("id","desc")->get();
        $_data = Array($arr_a,$arr_b,$arr_c);
        return json_encode($_data, JSON_UNESCAPED_UNICODE);
    }
    private function ListMsg($msg,$user_id,$type=null){
        $parent = $msg->post_user!=$user_id?$msg->post_user:$msg->get_user;
        if($type){
            return Array("id"=>$msg->id,"user"=>$msg->post_user,"time"=>$msg->created_at->format('Y-m-d H:i'),"content"=>$msg->content);
        }else{
            $MsgUser = User::find($parent);
            $MsgAvatar = Usermeta::where("user_id",$MsgUser->id)->where("key","avatar")->first();
            return Array("id"=>$msg->id,"parent"=>$parent,"name"=>$MsgUser->name,"avatar"=>$MsgAvatar->value,"time"=>$msg->created_at->format('Y-m-d H:i'),"content"=>$msg->content);
        }
    }
    public function GetMsg(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $_data = [];
            if($data["parent"]==0){
                if($data["num"]!=0){
                    $Msg = Message::where("status","<",2)->where('get_user', 0)->where('post_user', 1)->get();
                    foreach ($Msg as $_m){
                        $notice = Notice::where("user_id",$User->id)->where("msg_id",$_m->id)->first();
                        if(!$notice){
                            $notice = new Notice();
                            $notice->msg_id = $_m->id;
                            $notice->user_id = $User->id;
                            $notice->save();
                        }
                    }
                    $Msg = Message::where("status",0)->where(function($query) use ($User){
                        $query->where('get_user', $User->id)->orWhere('post_user', $User->id);
                    })->get();
                    foreach ($Msg as $_m){
                        $_m->status = 1;
                        $_m->save();
                    }
                }

                $Msg = Message::where("status","<",2)->where(function($query) use ($User){
                    $query->where(function($query) use ($User){
                        $query->where('get_user', 0)->where('post_user', 1);
                    })->orWhere(function($query) use ($User){
                        $query->where('get_user', $User->id)->where('post_user', 1);
                    })->orWhere(function($query) use ($User){
                        $query->where('get_user', 1)->where('post_user', $User->id);
                    });
                })->orderBy('id', 'desc')->first();
                if($Msg){
                    array_push($_data,$this->ListMsg($Msg,$User->id));
                }
                $Msg = Message::where("parent",0)->where("get_user",">",1)->where("post_user",">",1)->where(function($query) use ($User){
                    $query->where('get_user', $User->id)->orWhere('post_user', $User->id);
                })->orderBy('id', 'desc')->get();
                if($Msg){
                    foreach ($Msg as $M){
                        array_push($_data,$this->ListMsg($M,$User->id));
                    }
                }
            }else{
                $parent = $data["parent"];
                $Msg = Message::where("status","<",2);
                if($parent==1){
                    $Msg = $Msg->where(function($query) use ($User,$parent){
                        $query->where(function($query) use ($User,$parent){
                            $query->where('get_user', $User->id)->where('post_user', $parent);
                        })->orWhere(function($query) use ($User,$parent){
                            $query->where('get_user', $parent)->where('post_user', $User->id);
                        })->orWhere(function($query) use ($User,$parent){
                            $query->where('get_user', 0)->where('post_user', $parent);
                        });
                    })->get();
                }else{
                    $Msg = $Msg->where(function($query) use ($User,$parent){
                        $query->where(function($query) use ($User,$parent){
                            $query->where('get_user', $User->id)->where('post_user', $parent);
                        })->orWhere(function($query) use ($User,$parent){
                            $query->where('get_user', $parent)->where('post_user', $User->id);
                        });
                    })->get();
                }
                if($Msg){
                    foreach ($Msg as $M){
                        array_push($_data,$this->ListMsg($M,$User->id,true));
                    }
                    $MsgUser = User::find($parent);
                    $MsgAvatar = Usermeta::where("user_id",$MsgUser->id)->where("key","avatar")->first();
                    $_data = Array("list"=>$_data,"avatar"=>$MsgAvatar->value,"name"=>$MsgUser->name);
                }
            }
            return json_encode($_data, JSON_UNESCAPED_UNICODE);
        }
        return 0;
    }
    public function GetMsgNum(Request $request){
        $data = $request->input();
        $Num = 0;
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $Num = Message::where("get_user",$data["uid"])->where("status",0)->count();
            $Notices = Message::where("get_user",0)->where("post_user",1)->get();
            foreach ($Notices as $n){
                $_n = Notice::where("msg_id",$n->id)->where("user_id",$User->id)->first();
                if(!$_n){
                    $Num++;
                }
            }
        }
        return $Num;
    }
    public function PostMsg(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $Msg = new Message();
            $get_user = $data["get_user"];
            $Msg->post_user = $User->id;
            $Msg->get_user = $get_user;
            $Msg->content = $data["content"];

            $_Msg = Message::where("parent",0)->where(function($query) use ($User,$get_user){
                $query->where(function($query) use ($User,$get_user){
                    $query->where('get_user', $get_user)->where('post_user', $User->id);
                })->orWhere(function($query) use ($User,$get_user){
                    $query->where('get_user', $User->id)->where('post_user', $get_user);
                });
            })->first();

            $Msg->parent = $_Msg?$_Msg->id:0;
            if($Msg->save()){
                return $Msg->id;
            }
        }
        return 0;
    }
    public function GetTag(){
        $Tag = Tag::where("type","tag")->get();
        $Cat = Tag::where("type","page")->get();

        $id = Array();
        $name = Array();
        foreach ($Tag as $t){
            array_push($id,$t->id);
            array_push($name,$t->name);
        }
        $TagArr = Array("id"=>$id,"name"=>$name);

        $id = Array();
        $name = Array();
        foreach ($Cat as $c){
            array_push($id,$c->id);
            array_push($name,$c->name);
        }
        $CatArr = Array("id"=>$id,"name"=>$name);
        $_data = Array("tags"=>$TagArr,"cats"=>$CatArr);
        return json_encode($_data, JSON_UNESCAPED_UNICODE);
    }
    public function PostActive(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $_data = json_decode($data["data"]);
            $tag = Tag::where("type","xcx")->where("name",$data["type"])->first();
            $Post = new Post();
            $Post->title = $_data->name;
            $Post->cover = asset('img/shen.jpg');
            $Post->user_id = $User->id;
            $Post->author = $User->name;
            $Post->xcx = $tag->id;
            $Post->tag = $data["cat"];
            $Post->content = $_data->content;
            $Post->status = 0;
            if($Post->save()){

                foreach($_data as $key => $value) {
                    if($key!="content"||$key!="name"){
                        $Meta = new Postmeta();
                        $Meta->post_id = $Post->id;
                        $Meta->key = $key;
                        $Meta->value = $value;
                        $Meta->save();
                    }
                }
                $tagNew = json_decode($data["arr"]);
                $arrLength = count($tagNew);
                for ($i=0;$i<$arrLength;$i++){
                    $newTag = new TagGroup();
                    $newTag->post_id = $Post->id;
                    $newTag->tag = $tagNew[$i];
                    $newTag->save();
                }
                $Form = new Form();
                $Form->user_id = $User->id;
                $Form->name = $User->name;
                $Form->form = $data["data"];
                $Form->type = "active";
                $Form->status = 0;
                $Form->item = 0;
                $Form->parent = $Post->id;
                $Form->save();
                return $Form->id;
            }
        }
        return 0;
    }
    public function GetForm(Request $request){
        $data = $request->input();
        $formId = Postmeta::where('post_id',$data["id"])->where('key','form')->first();
        $arr = Array('id'=>0,'value'=>[]);
        if($formId){
            $FormItem = Formitem::find($formId->value);
            if($FormItem){
                $arr['value'] = json_decode($FormItem->value);
                $arr['id'] =json_decode($formId->value);
            }
        }
        return json_encode($arr, JSON_UNESCAPED_UNICODE);
    }
    public function PostForm(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $Form = new Form();
            $Form->user_id = $User->id;
            $Form->name = $User->name;
            if(isset($data["info"])){
                $arr = Array();
                array_push($arr,$User->real_name);
                array_push($arr,$User->phone);
                array_push($arr,$User->company);
                array_push($arr,$User->content);
                $Form->form = json_encode($arr, JSON_UNESCAPED_UNICODE);
            }else{
                $Form->form = $data["data"];
            }
            $Form->type = $data["type"];
            $Form->status = 0;
            $Form->parent = $data["parent"];
            $Form->item = $data["id"];
            if($Form->save()){
                if($data["parent"]!="0"){
                    $meta = Postmeta::where("post_id",$data["parent"])->where("key","smsPhone")->first();
                    if($meta){
                        if($data["id"]!=0){
                            $items = Formitem::find($data["id"]);
                            $name = Array();
                            $item = json_decode($items->value);
                            for ($i=0;$i<count($item);$i++){
                                array_push($name,$item[$i]->name);
                            }
                        }else{
                            $name = ["联系人","联系电话","公司信息","公司简介"];
                        }
                        $d = json_decode($Form->form);
                        $num = count($d);
                        $str = "";
                        for ($i=0;$i<$num;$i++){
                            if($d[$i]){
                                $str = $str.$name[$i].":".$d[$i]." ";
                            }
                        }
                        $arr = [$str];
                        $SMS = new SendFormSMS();
                        $SMS->SendSMS($meta->value,$arr,'171564');
                    }
                }
                return $Form->id;
            }
        }
        return 0;
    }
    public function upLevel(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $d = json_decode($data["data"]);
            if(isset($data["level"])){
                $User->level=$data["level"];
                $User->company=$d[2];
                $User->content=$d[3];
            }else{
                $User->level=2;
            }
            $User->real_name=$d[0];
            $User->phone=$d[1];
            if($User->save()){
                return 1;
            }
            return 0;
        }
        return 0;
    }
    public function HomeService(){
        $id = [15,14,16];
        $num = Array();
        for ($i=0;$i<3;$i++){
            $n = Post::where("tag",$id[$i])->where("status",1)->count();
            array_push($num,$n);
        }
        $Swipe_id = Array();
        $Swipe_cover = Array();
        $Swipe_title = Array();
        $Swipe_to = Array();
        $Swipe = Post::where("xcx",1)->where("level",2)->where("status",1)->orderBy('id', 'desc')->get();
        if($Swipe){
            foreach ($Swipe as $s){
                $url = Postmeta::where("key","toUrl")->where("post_id",$s->id)->first();
                $to = $url?$url->value:"";
                array_push($Swipe_id,$s->id);
                array_push($Swipe_cover,$s->cover);
                array_push($Swipe_title,$s->title);
                array_push($Swipe_to,$to);
            }
        }
        $SwipeArr = array('id'=>$Swipe_id,'pic'=>$Swipe_cover,'title'=>$Swipe_title,'to'=>$Swipe_to);
        $_data= array('swipe'=>$SwipeArr,'num'=>$num);
        return $_data;
    }
    public function SMS(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $Phone = $data["Phone"];
            $code = $this->RandomString();
            $arr = [$code,"5"];
            $SMS = new SendTemplateSMS();
            $msg = $SMS->SendSMS($Phone,$arr,'158289');
            if($msg){
                return $code;
            }
        }
        return 0;
    }
    public function GetNews(Request $request){
        $data = $request->input();
        $type = $data["type"];
        $ConId = $request->has('conId')?$data["conId"]:0;
        $TopLength= $request->has('top')?$data["top"]:0;
        $MenuLength = $request->has('menu')?$data["menu"]:0;

        $Menu_id = Array();
        $Menu_name = Array();

        $content_id = Array();
        $content_cover = Array();
        $content_title = Array();
        $content_time = Array();
        $content_author = Array();

        if($MenuLength == 0){
            $Menu = Tag::where("type","page")->get();
            if($Menu){
                foreach ($Menu as $m){
                    array_push($Menu_id,$m->id);
                    array_push($Menu_name,$m->name);
                }
            }
        }
        $MenuArr = array('id'=>$Menu_id,'name'=>$Menu_name);

        $TopNew = 0;
        if($type == 0){
            if($TopLength == 0){
                $TopNew = Post::where("xcx",1)->where("level",1)->where("status",1)->orderBy('id', 'desc')->get();
            }

            if($ConId == 0){
                $content = Post::where("xcx",1)->where("level","<>",1)->where("status",1)->orderBy('id', 'desc')->simplePaginate(20);
            }else{
                $content = Post::where("xcx",1)->where("id","<",$ConId)->where("level","<>",1)->where("status",1)->orderBy('id', 'desc')->simplePaginate(20);
            }
        }else{
            if($TopLength == 0){
                $TopNew = Post::where("xcx",1)->where("tag",$type)->where("level",1)->where("status",1)->orderBy('id', 'desc')->get();
            }

            if($ConId == 0){
                $content = Post::where("xcx",1)->where("tag",$type)->where("level","<>",1)->where("status",1)->orderBy('id', 'desc')->simplePaginate(20);
            }else{
                $content = Post::where("xcx",1)->where("tag",$type)->where("id","<",$ConId)->where("level","<>",1)->where("status",1)->orderBy('id', 'desc')->simplePaginate(20);
            }
        }
        if($TopNew){
            foreach ($TopNew as $t){
                array_push($content_id,$t->id);
                array_push($content_cover,$t->cover);
                array_push($content_title,$t->title);
                array_push($content_time,$t->created_at->format('Y-m-d H:i'));
                array_push($content_author,$t->author);
            }
        }
        if($content){
            foreach ($content as $c){
                array_push($content_id,$c->id);
                array_push($content_cover,$c->cover);
                array_push($content_title,$c->title);
                array_push($content_time,$c->created_at->format('Y-m-d H:i'));
                array_push($content_author,$c->author);
            }
        }
        $conArr = array('id'=>$content_id,'pic'=>$content_cover,'title'=>$content_title,'time'=>$content_time,'author'=>$content_author);
        $_data= array('menu'=>$MenuArr,'content'=>$conArr);
        return json_encode($_data, JSON_UNESCAPED_UNICODE);
    }
    public function FY(Request $request){
        $data = $request->input();
        $phone = $data["phone"];
        $id = $data["id"];
        $ret = null;

        $feiyuApi = new FeiyuApi();
        $ret = $feiyuApi->callBackUrlAction($id,'86'.$phone);
        return $ret;

    }
    public function GetShop(Request $request){
        $data = $request->input();
        $id = $data['id'];
        $shop = ShopUser::find($id);
        if(isset($data['con'])&&$data['con']){
            $_r = $shop->content;
        }else{
        $shop->content = preg_replace('/&nbsp;/', ' ', $shop->content);
        $_arr = preg_split('/(<img.*?>)/i', $shop->content, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
        $_r = array();
        foreach($_arr as $_txt) {
            if(substr($_txt, 0, 4) == '<img') {
                $_matchs = array();
                preg_match('/<img.*?src="(.*?)"/i', $_txt, $_matchs);
                $_txt = $_matchs[1];
                $_r[]= array('type'=>'img', 'data'=>$_txt);
            }else {
                $_r[]= array('type'=>'txt', 'data'=>$_txt);
            }
        }
        }
        $con= array('name'=>$shop->name,'address'=>$shop->address,'summary'=>$shop->summary,'content'=> $_r,'cover'=> $shop->cover,'phone'=> $shop->phone);
        $meta = Array();
        $Shopmeta = Shopmeta::where("shop_id",$id)->get();
        foreach ($Shopmeta as $m){
            $meta["$m->key"]= $m->value;
        }
        if(isset($meta['startService'])&&isset($meta['endService'])){
            $now_time  = date('H:i');
            $meta['callStatus']= $now_time>$meta['startService']&&$now_time<$meta['endService']?1:0;
        }else{
            $meta['callStatus']= 0;
        }

        $cats = ShopCat::where("parent_id",$id)->orderBy('order_id','asc')->get();
        $catsArr = [];
        $goodsArr = [];
        foreach ($cats as $cat){
            Array_push($catsArr,$cat->name);
            $_gArr = ShopGoods::where('cat',$cat->id)->where('status',1)->orderBy('created_at', 'desc')->get();
            $_gs = [];
            foreach ($_gArr as $_g){
                Array_push($_gs,Array('id'=>$_g->id,'name'=>$_g->name,'price'=>$_g->price,'summary'=>$_g->more,'kind'=>$_g->kind));
            }
            Array_push($goodsArr,$_gs);
        }
        $_data= array('content'=>$con,'meta'=>$meta,'cat'=>$catsArr,'goods'=>$goodsArr);
        return json_encode($_data, JSON_UNESCAPED_UNICODE);
    }
    public function GetOrder(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $address = Usermeta::where('user_id',$data["uid"])->where('key','address')->first();
            $limit = Shopmeta::where("shop_id",$data["id"])->where("key","coupon_use_limit")->first();
            $coupon_id = $limit?[$data["id"]]:[$data["id"],0];
            $Coupon = ShopCoupon::where('user_id',$data["uid"])->whereIn('coupon_id',$coupon_id)->where('status',1)->get();
            return json_encode(Array("address"=>($address?$address->value:""),"coupon"=>$Coupon), JSON_UNESCAPED_UNICODE);
        }
        return 0;
    }

    private function getOutTradeNO($type, $id)
    {
        // 微信 out_trade_no 不允许有 '.'
        return str_replace('.', '', uniqid(sprintf('%s%s', $type, $id), true));
    }

    public function PostOrder(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            if(isset($data["parent"])){
                $Order = ShopOrder::find($data["parent"]);
                $trade = $this->getOutTradeNO($Order->type, $Order->post_id);
                Log::info('[P] out_trade_no: '.$trade);
                $jsApi = new JsApi_pub();
                $unifiedOrder = new UnifiedOrder_pub();
                $unifiedOrder->setParameter("openid","$User->openid");//用户openid
                $unifiedOrder->setParameter("body","$Order->body");//商品描述
                $unifiedOrder->setParameter("out_trade_no","$trade");//商户订单号
                $unifiedOrder->setParameter("total_fee",$Order->total*100);//总金额
                $unifiedOrder->setParameter("notify_url",\App\WxPay\WxPayConf_pub::NOTIFY_URL);//通知地址
                $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
                $prepay_id = $unifiedOrder->getPrepayId();
                $jsApi->setPrepayId($prepay_id);
                $jsApiParameters = $jsApi->getParameters("$trade");
                $Order->trade = $trade;
                $Order->save();
                return $jsApiParameters;
            }else{
                $trade = $this->getOutTradeNO($data['type'], $data['id']);
                Log::info('[N] out_trade_no: '.$trade);
                $total = json_decode($data["total"]);
                $shop = json_decode($data["shopInfo"]);

                $Order = new ShopOrder();
                $Order->user_id = $data["uid"];
                $Order->post_id = $data["id"];
                $Order->type = $data["type"];
                $Order->trade = $trade;
                $Order->total = $total->total;
                $Order->body = $shop->name."的订单";
                $Order->content = json_encode(Array("list"=>json_decode($data["list"]),"address"=>json_decode($data["address"]),"coupon"=>json_decode($data["coupon"]),"shopInfo"=>$shop,"total"=>$total,"time"=>$data["time"],"pay"=>$data["pay"],"note"=>(isset($data["note"])?$data["note"]:'')), JSON_UNESCAPED_UNICODE);
                if($Order->save()){
                    if($data["coupon"]!='""'){
                        $CouponData = json_decode($data["coupon"]);
                        if($data["type"] == 'coupon'){
                            $Coupon = ShopCode::find($CouponData->id);
                        }else{
                            $Coupon = ShopCoupon::find($CouponData->id);
                        }
                        if($Coupon){
                            $Coupon->status = 0;
                            $Coupon->save();
                        }
                    }
                    if($total->total!=0){
                        $jsApi = new JsApi_pub();
                        $unifiedOrder = new UnifiedOrder_pub();
                        $unifiedOrder->setParameter("openid","$User->openid");//用户openid
                        $unifiedOrder->setParameter("body",$shop->name."的订单");//商品描述
                        $unifiedOrder->setParameter("out_trade_no",$trade);//商户订单号
                        $unifiedOrder->setParameter("total_fee",$total->total*100);//总金额
                        $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
                        $prepay_id = $unifiedOrder->getPrepayId();
                        $jsApi->setPrepayId($prepay_id);
                        $jsApiParameters = $jsApi->getParameters($trade);
                        return $jsApiParameters;
                    }else{
                        return $trade;
                    }
                }
            }
        }
        return 0;
    }
    public function PostAddress(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $address = Usermeta::where('user_id',$data["uid"])->where('key','address')->first();
            if($address){
                $address->value = $data["address"];
            }else{
                $address = new Usermeta();
                $address->user_id = $data["uid"];
                $address->key = 'address';
                $address->value = $data["address"];
            }
            if($address->save()){
                return $address->id;
            }
        }
        return 0;
    }
    public function GetCoupon(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            if($data["type"]=="info"){
                $coupon = ShopCoupon::where("user_id",$data["uid"])->where("post_id",$data["id"])->get();
                $num = count($coupon);
                $_data = Array("coupon"=>[],"num"=>$num);
                return json_encode($_data, JSON_UNESCAPED_UNICODE);
            }elseif($data["type"]=="use"){
                $coupon = ShopCoupon::where("user_id",$data["uid"])->where("coupon_id",$data["id"])->get();
                $num = count($coupon);
                $_data = Array("coupon"=>$coupon?$coupon:[],"num"=>$num);
                return json_encode($_data, JSON_UNESCAPED_UNICODE);
            }else{
                $coupon = ShopCoupon::where("user_id",$data["uid"])->get();
                return json_encode($coupon, JSON_UNESCAPED_UNICODE);
            }
        }
        return 0;
    }
    public function PostCoupon(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $Meta = Postmeta::where("post_id",$data["id"])->whereIn("key",["coupon_id","coupon_discount","coupon_cash","coupon_cut","coupon_full","startCoupon","endCoupon","coupon_type"])->get();
            $Post = Post::find($data["id"]);
            $CouponInfo = [];
            foreach ($Meta as $m){
                $CouponInfo["$m->key"] = $m->value;
            }
            if(isset($CouponInfo["coupon_discount"])){
                $cat = "discount";
                $content = $CouponInfo["coupon_discount"];
            }elseif (isset($CouponInfo["coupon_cash"])){
                $cat = "cash";
                $content = $CouponInfo["coupon_cash"];
            }else{
                $cat = "cut";
                $content = json_encode(Array("full"=>$CouponInfo["coupon_full"],"cut"=>$CouponInfo["coupon_cut"]), JSON_UNESCAPED_UNICODE);
            }

            $Coupon = new ShopCoupon();
            $Coupon->user_id = $data["uid"];
            $Coupon->post_id = $data["id"];
            $Coupon->coupon_id = $CouponInfo["coupon_id"];
            $Coupon->startTime = $CouponInfo["startCoupon"];
            $Coupon->endTime  = $CouponInfo["endCoupon"];
            $Coupon->title = $Post->title;
            $Coupon->cat = $cat;
            $Coupon->type = $CouponInfo["coupon_type"];
            $Coupon->content = $content;
            if($Coupon->save()){
                $meta = Postmeta::where("post_id",$data["id"])->where("key","coupon_num")->first();
                $meta->value--;
                $meta->save();
                return $Coupon->id;
            }
        }
        return 0;
    }
    public function UserOrder(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            if(isset($data["id"])){
                $Order = ShopOrder::find($data["id"]);
                if($Order->type=='shop'){
                    $more = ShopUser::find($Order->post_id);
                    $Order->name = $more->name;
                    $Order->address = $more->address;
                }else{
                    $more = Post::find($Order->post_id);
                    $Order->name = $more->author;
                }
                $Order->cover = $more->cover;
                $Order->content = json_decode($Order->content);
            }else{
                $Order = ShopOrder::where("user_id",$data["uid"])->orderBy("id","desc")->get();
                foreach ($Order as $o){
                    if($o->type=='shop'){
                        $more = ShopUser::find($o->post_id);
                        $o->name = $more->name;
                        $o->address = $more->address;
                    }else{
                        $more = Post::find($o->post_id);
                        $o->name = $more->author;
                    }
                    $o->cover = $more->cover;
                    $o->content = json_decode($o->content);
                }
            }
            return $Order;
        }
        return 0;
    }
    public function DelOrder(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $Order = ShopOrder::find($data["parent"]);
            $Order->status = 2;
            if($Order->save()){
                return $Order->id;
            }
        }
        return 0;

    }
    public function PaySuccess(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $Order = ShopOrder::where("trade",$data["trade"])->where("user_id",$data["uid"])->first();
            if($Order&&$data["price"]=='0'){
                $Order->status = 1;
                if($Order->save()){
                    $this->orderCoupon($Order);
                    return $Order->id;
                }
            }
        }
        return '';
    }
    private function orderCoupon($Order){
        if($Order->type != 'coupon'){
            $info = json_decode($Order->content);
            if($info->coupon){
                $coupon = ShopCoupon::find($info->coupon->id);
                if($coupon){
                    $coupon_code = Postmeta::where("post_id",$coupon->post_id)->where("key","coupon_code")->first();
                    if($coupon_code){
                        $rand = $this->getCouponCode();
                        $code = new ShopCode();
                        $code->order_id = $Order->id;
                        $code->code = $rand;
                        $code->coupon_id = $info->coupon->id;
                        $code->shop_id = $Order->post_id;
                        if($code->save()){
                            $Message = new Message();
                            $Message -> post_user = 1;
                            $Message -> status = 0;
                            $shop_user_id = '';
                            if($Order->type == 'shop'){
                                $shop = ShopUser::find($Order->post_id);
                                $shop_user_id = $shop?$shop->user_id:'';
                            }elseif ($Order->type == 'service'){
                                $shop = Postmeta::where("post_id",$Order->post_id)->where("key","admin")->first();
                                $shop_user_id = $shop?$shop->value:'';
                            }
                            if($shop_user_id){
                                $Message -> content = '你收到一个优惠码  '.$rand.' ，可在后台查看';
                                $_Msg = Message::where("parent",0)->where(function($query) use ($shop_user_id){
                                    $query->where(function($query) use ($shop_user_id){
                                        $query->where('get_user', $shop_user_id)->where('post_user', 1);
                                    })->orWhere(function($query) use ($shop_user_id){
                                        $query->where('get_user', 1)->where('post_user', $shop_user_id);
                                    });
                                })->first();
                                $Message->get_user = $shop_user_id;
                                $Message->parent = $_Msg?$_Msg->id:0;
                                $Message -> save();
                            }
                        }
                    }
                }
            }
        }else{
            $Meta = Postmeta::where("post_id",$Order->post_id)->whereIn("key",["coupon_id","coupon_discount","coupon_cash","coupon_cut","coupon_full","startCoupon","endCoupon","coupon_type"])->get();
            $Post = Post::find($Order->post_id);
            $CouponInfo = [];
            foreach ($Meta as $m){
                $CouponInfo["$m->key"] = $m->value;
            }
            if(isset($CouponInfo["coupon_discount"])){
                $cat = "discount";
                $content = $CouponInfo["coupon_discount"];
            }elseif (isset($CouponInfo["coupon_cash"])){
                $cat = "cash";
                $content = $CouponInfo["coupon_cash"];
            }else{
                $cat = "cut";
                $content = json_encode(Array("full"=>$CouponInfo["coupon_full"],"cut"=>$CouponInfo["coupon_cut"]), JSON_UNESCAPED_UNICODE);
            }

            $Coupon = new ShopCoupon();
            $Coupon->user_id = $Order->user_id;
            $Coupon->post_id = $Order->post_id;
            $Coupon->coupon_id = $CouponInfo["coupon_id"];
            $Coupon->startTime = $CouponInfo["startCoupon"];
            $Coupon->endTime  = $CouponInfo["endCoupon"];
            $Coupon->title = $Post->title;
            $Coupon->cat = $cat;
            $Coupon->type = $CouponInfo["coupon_type"];
            $Coupon->content = $content;
            if($Coupon->save()){
                $meta = Postmeta::where("post_id",$Order->post_id)->where("key","coupon_num")->first();
                $meta->value--;
                $meta->save();
            }
        }
    }
    private function getCouponCode(){
        $randStr = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
        $rand = substr($randStr,0,12);
        $code = ShopCode::where("code",$rand)->first();
        if($code){
            return $this->getCouponCode();
        }else{
            return $rand;
        }
    }
    public function wxnotify(){
        $xml = file_get_contents("php://input");
        $notify = new Notify_pub();
        $notify->saveData($xml);

        if($notify->checkSign() == FALSE){
            $notify->setReturnParameter("return_code","FAIL");//返回状态码
            $notify->setReturnParameter("return_msg","签名失败");//返回信息
        }else{
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
            if ($notify->data["return_code"] == "SUCCESS"&&$notify->data["result_code"] == "SUCCESS") {
                $Order = ShopOrder::where("trade",$notify->data["out_trade_no"])->first();
                if($Order){
                    $Order->transaction = $notify->data["transaction_id"];
                    $Order->status = 1;
                    $Order->save();
                    $this->orderCoupon($Order);
                    $info = json_decode($Order->content);
                    if($info->shopInfo->phone){
                        $Phone = $info->shopInfo->phone;
                        $num = count($info->list->item);
                        $str = "";
                        for ($i=0;$i<$num;$i++){
                            if($i>0){
                                $str = $str . "、";
                            }
                            $str = $str . $info->list->item[$i]->name . "(x" . $info->list->num[$i] .")";
                        }
                        if(isset($info->note)&&$info->note){
                            $str = $str .'。买家留言：'.$info->note;
                        }
                        $arr = [$str,$info->address->address,$info->address->phone];
                        $SMS = new SendShopSMS();
                        $SMS->SendSMS($Phone,$arr,'165440');
                    }
                }
            }
        }
        $returnXml = $notify->returnXml();
        return $returnXml;
    }
    public function GetShopOrder(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $Shop = ShopUser::where("user_id",$User->id)->first();
            if($Shop){
                $year = date('Y');
                $start_date = date('d-m-Y', strtotime('01-'.$data["month"].'-'.$year));
                $end_date = date('d-m-Y', strtotime(date('01-m-Y', strtotime($start_date)) . ' +1 month'));
                $str_start_date = date("Y-m-d H:i:s",strtotime($start_date));
                $str_end_date = date("Y-m-d H:i:s",strtotime($end_date));
                $Order = ShopOrder::where("post_id",$Shop->id)->where("type","shop")
                    ->where("status",1)
                    ->where('created_at','>=',"$str_start_date")
                    ->where('created_at','<=',"$str_end_date")
                    ->orderBy("id","desc")
                    ->get();
                $Count = 0;
                foreach ($Order as $o){
                    $o->content = json_decode($o->content);
                    $Count += $o->total;
                };
                return json_encode(Array("order"=>$Order,"count"=>$Count), JSON_UNESCAPED_UNICODE);
            }
        }
        return 0;
    }
    public function MetaSuccess(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $Order = ShopOrder::find($data["id"]);
            if($Order){
                $Order->meta = 1;
                if($Order->save()){
                    return $Order->id;
                }
            }
        }
        return 0;

    }
    public function PostLive(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $live = new Live();
            $live->user_id = $User->id;
            $live->type = $data["type"];
            $live->content = $data["content"];
            $live->parent_id = $data["parent_id"];
            $live->more = isset($data["more"])?$data["more"]:"";
            if($live->save()){
                return $live->id;
            }
        }
        return 0;

    }
    public function GetLive(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $Users = [];
            if($data["userNum"]==0){
                $LiveUser = LiveUser::where("user_id",$User->id)->where("parent_id",$data["id"])->first();
                if(!$LiveUser){
                    $LiveUser = new LiveUser();
                    $LiveUser->user_id = $User->id;
                    $LiveUser->parent_id = $data["id"];
                    $LiveUser->save();
                }
            }
            $LiveCount = LiveUser::where("parent_id",$data["id"])->count();
            if($LiveCount!=$data["userNum"]){
                $LiveUsers = LiveUser::where("id",">",$data["userLastId"])->where("parent_id",$data["id"])->get();
                foreach ($LiveUsers as $u){
                    $avatar = Usermeta::where("user_id",$u->user_id)->where("key","avatar")->first();
                    $user = User::find($u->user_id);
                    $img = $avatar?$avatar->value:"https://sichuangyi.demopp.in/upload/avatar/avatar.png";
                    $_u = Array("id"=>$u->id,"user_id"=>$u->user_id,"name"=>$user->name,"avatar"=>$img);
                    array_push($Users,$_u);
                }
            }
            $Lives = Live::where("id",">",$data["liveId"])->where("parent_id",$data["id"])->get();
            $_data = Array("userList"=>$Users,"count"=>$LiveCount,"list"=>$Lives,"num"=>$data["userNum"]);
            return json_encode($_data, JSON_UNESCAPED_UNICODE);
        }
        return 0;

    }
    public function UserForm(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $Form = Form::find($data["id"]);
            $value = json_decode($Form->form);
            $name = Array();
            if($Form->item){
                $items = Formitem::find($Form->item);
                $item = json_decode($items->value);
                for ($i=0;$i<count($item);$i++){
                    if($item[$i]->type === 'title')continue;
                    array_push($name,$item[$i]->name);
                }
            }else{
                $name = ["联系人","联系电话","公司信息","公司简介"];
            }
            $page = Post::find($Form->parent);
            return json_encode(Array("name"=>$name,"value"=>$value,"title"=>$page->title), JSON_UNESCAPED_UNICODE);
        }
        return 0;

    }
    public function liveVerify(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $status = LiveUser::where("user_id",$User->id)->where("parent_id",$data["id"])->first();
            if($status){
                return 1;
            }else{
                $form = Form::where("user_id",$User->id)->where("parent",$data["id"])->first();
                if($form){
                    return 2;
                }
            }
        }
        return 0;

    }
    public function verifyForm(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $status = Form::where("user_id",$User->id)->where("parent",$data["id"])->first();
            if($status){
                return 1;
            }
        }
        return '';
    }
    public function verifyCode(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $code = ShopCode::where("code",$data["code"])->where("status",1)->first();
            if($code){
                $coupon = ShopCoupon::find($code->coupon_id);
                if($coupon){
                    $price = Postmeta::where("post_id",$coupon->post_id)->where("key","coupon_code")->first();
                    if($price){
                        return Array("id" => $code->id ,"price"=>$price->value);
                    }
                }
            }
        }
        return '';
    }
}
